JAVA Learn quickly guide Programming a chopped (first edition) by Psen Poul Klausen

JAVA Learn quickly guide Programming a chopped (first edition) by Psen Poul Klausen

Author:Psen Poul Klausen [Poul Klausen, Psen]
Language: eng
Format: azw3
Publisher: UNKNOWN
Published: 2017-09-06T04:00:00+00:00


The following program creates an array with 5 integers of the type int and initializes the elements with random numbers, then the numbers are printed on the screen:

package array05;

import java.util.*;

public class Array05 {

private static Random rand = new Random(); public static void main(String[] args) {

int[] arr = new int[5];

for (int i = 0; i < arr.length; ++i) arr[i] = rand.nextInt(); for (int i = 0; i < arr.length; ++i) System.out.println(arr[i]);

}

}

The program has a random number generator and creates an array with space for 5 elements of the type int. Next, the array is filled with random integers. This is done with a for loop, which is a control structure that I have not yet mentioned, but it is easy enough to understand how it works. It has three parts. In the first part defines a variable that is initialized to 0. The second part is a condition that tests whether the value of the variable i is less than the number of elements in the array. You must specifically noting how one refers to the number of elements in an array as

arr.length

If the condition is true, the statement after the for statement is executed, which here is

arr[i] = rand.nextInt(); This means that the i-th element in the array is assigned a value. Next, the third part of the for statement is executed that add 1 to the variable i, and then the statement test the condition again and everything repeats itself. Since the variable i for each iteration is 1 higher, all places in the array are referenced until there are no more. main() has another for statement, and it works in principle the same way. It runs through all the array’s elements place for place. The first for statement initialize the elements, while the other prints them.

As another example, the following program defines an array with three elements of the type String and prints them:

package array06; public class Array06 {

public static void main(String[] args) {

String[] arr = { "Svend", "Knud", "Valdemar" };

for (int i = 0; i < arr.length; ++i) System.out.println(arr[i]); }

}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.